<template>
  <el-card class="box-card el-card-flex">
    <div slot="header" class="clearfix">
      <span>
        <i class="el-icon-monitor"></i>
        系统管理
      </span>
    </div>
    <!-- 表单 -->
    <div class="text item">
      <el-form :inline="true" :model="formInlineSearch" class="demo-form-inline" @submit.native.prevent>
        <el-form-item label="">
          <el-input clearable v-model="formInlineSearch.textSearch" placeholder="请输入系统编码/名称" style="width:240px;" @keyup.enter.native="domainTable(1, 20)" @clear="domainTable">
            <el-button slot="append" icon="el-icon-search" @click="domainTable(1, 20)"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="advancedSearch">
						高级查询
						<i class="el-icon-magic-stick"></i>
					</el-button>
        </el-form-item>
        <el-form-item style="float:right">
					<el-button type="primary" plain @click="handleAdd">
            新增
            <i class="el-icon-plus"></i>
          </el-button>
				</el-form-item>
      </el-form>
      <!-- tabel表格 -->
      <div class="el-flex el-box-column">
        <el-table
          :data="domainTabelData"
          border
          stripe
          style="width: 100%"
          height="100%"
          ref="areaRefTable"
        >
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="domainCode" label="系统编码"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="domainName" label="系统名称"></el-table-column>
          <el-table-column min-width="120px" sortable :show-overflow-tooltip="true" prop="domainDesc" label="系统说明"></el-table-column>
          <el-table-column width="110" sortable prop="domainStatus" label="系统状态" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.domainStatus" active-value="Y" inactive-value="N" @change="appStatusclick(scope.$index, scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column width="70" prop="control" label="操作" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" type="text" title="修改系统管理" @click="handleEdit(scope.$index, scope.row)"><i class="el-icon-edit"></i></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 编辑/新增弹框 -->
    <el-dialog :title="modalTitle" :visible.sync="dialogVisible" :before-close="handleClose" :close-on-click-modal="false" :close-on-press-escape="false">
      <!-- <div class="container" style="overflow: auto;height: 380px;"> -->
        <el-form label-width="100px" :model="domainFormInline" ref="domainFormInline" class="demo-form-inline">
          <el-form-item
            label="系统编码:"
            prop="domainCode"
            :rules="[
              {
                required: true,
                message: '系统编码不能为空',
                trigger: 'blur'
              }
            ]"
          >
            <el-col :span="12">
              <el-input v-model="domainFormInline.domainCode" placeholder="请输入系统编码" :readonly="readonly"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item
            label="系统名称:"
            prop="domainName"
            :rules="[
              {
                required: true,
                message: '系统名称不能为空',
                trigger: 'blur'
              }
            ]"
          >
            <el-col :span="15">
              <el-input v-model="domainFormInline.domainName" placeholder="请输入系统名称"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="系统说明:" prop="domainDesc">
            <el-col :span="20">
              <el-input type="textarea" :rows="2" v-model="domainFormInline.domainDesc" placeholder="请输入系统说明"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="系统状态:" prop="domainStatus">
            <el-switch v-model="domainFormInline.domainStatus" active-value="Y" inactive-value="N"></el-switch>
          </el-form-item>
        </el-form>
        <div class="el-flex el-box-column">
          <div style="margin-bottom: 8px;">
            <div class="btns" style="float: right;">
              <!-- <el-button type="primary" plain @click="addAuthorization">
                新增授权
                <i class="el-icon-plus"></i>
              </el-button> -->
            </div>
          </div>
          <!-- <el-table
            :data="authorizationData"
            border
            stripe
            style="width: 100%"
            ref="areaRefTable"
          >
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" fixed prop="userName" label="用户名"></el-table-column>
            <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="empName" label="员工姓名"></el-table-column>
            <el-table-column min-width="100px" sortable prop="control" label="操作" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" type="text" title="删除用户信息" @click="handleDelete(scope.$index, authorizationData)"><i class="el-icon-delete"></i></el-button>
            </template>
          </el-table-column>
          </el-table> -->
        </div>
        <!-- 分页 -->
        <!-- <el-pagination
          background
          :current-page="nowPageNum"
          @current-change="currentChange"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total"
        ></el-pagination> -->
      <!-- </div> -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSave">保存 <i class="el-icon-document-checked el-icon--right"></i></el-button>
        <el-button type="danger" @click="handleCheck(false)">关闭 <i class="el-icon-close"></i></el-button>
      </span>
    </el-dialog>
    <!-- 新增授权弹框 -->
    <el-dialog title="新增授权"
      :visible.sync="dialogAddVisible"
      :before-close="handleAddClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      custom-class="el-dialog-flex">
      <div class="el-flex el-box-column"
    >
        <el-input clearable v-model="textSearchUser" placeholder="请输入用户名/别名" style="width:280px;" @keyup.enter.native="addAuthorizationEvent" @clear="addAuthorizationEvent">
					<el-button slot="append" icon="el-icon-search" @click="addAuthorizationEvent"></el-button>
				</el-input>
        <el-table
          :data="areaData"
          border
          stripe
          ref="areaRefTable"
          style="width: 100%;margin-top:10px;margin-bottom:10px"
          @selection-change="handleSelectionChange"
          height="100%"
        >
          <el-table-column type="selection" align="center"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" fixed prop="userName" label="用户名"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="name" label="员工姓名"></el-table-column>
        </el-table>
        <!-- 分页 -->
				<el-pagination
					background
					@size-change="handleSizeUserChange"
					:current-page="currentUserPage"
					@current-change="handleCurrentUserChange"
					:page-size="pageUserSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="totalUser"
				></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handDomainleSure">
          确定
          <i class="el-icon-document-checked el-icon--right"></i>
        </el-button>
        <el-button @click="handleCloseCheck(false)">
          取消
          <i class="el-icon-refresh-left"></i>
        </el-button>
      </span>
    </el-dialog>
    <!-- 高级查询抽屉式弹框 -->
    <el-drawer
      title="高级查询"
      :visible.sync="dialogSearch"
      :before-close="searchClose"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
			:wrapperClosable="true"
      :close-on-press-escape="false"
    >
      <div class="demo-drawer__content el-box-column" style="height: 100%; margin-left: 6px;">
        <el-form label-width="100px" :model="formInline" ref="formInline" class="el-flex">
          <el-form-item label="系统编码:" prop="domainCode">
            <el-col :span="9">
              <el-input v-model="formInline.domainCode" placeholder="请输入系统编码"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="系统名称:" prop="domainName">
            <el-col :span="12">
              <el-input v-model="formInline.domainName" placeholder="请输入系统名称" auto-complete="off"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="系统状态:" prop="domainStatus">
            <!-- <el-switch v-model="formInline.domainStatus" active-value="Y" inactive-value="N"></el-switch> -->
            <el-radio-group v-model="formInline.domainStatus">
              <el-radio border label="">全部</el-radio>
              <el-radio border label="Y">启用</el-radio>
              <el-radio border label="N">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer" style="text-align: right; margin-bottom: 10px; padding-right:10px;">
          <el-button type="primary" @click="domainTable(1, 20)">
            确定
            <i class="el-icon-document-checked el-icon--right"></i>
          </el-button>
          <el-button @click="handleSearchClose">
            重置
            <i class="el-icon-refresh-left"></i>
          </el-button>
        </div>
      </div>
    </el-drawer>
  </el-card>
</template>
<script>
import { Tree, Dialog, Table, TableColumn, Pagination, MessageBox, Message, Drawer } from 'element-ui'
import { ccmsDomainsList, updateCcmsDomainById, insertCcmsDomain, getDomainUser, cancelDomainAuth, userList } from '@/api/authority/areaManage/areaManage.js'
export default {
  name: 'areaManage',
  components: {
    'el-tree': Tree, // 树形菜单
    'el-dialog': Dialog, // 对话框
    'el-table': Table, // 表格
    'el-table-column': TableColumn, // 表格列
    'el-pagination': Pagination, // 分页
    'el-drawer': Drawer,
  },
  data () {
    let domainInlineVal = {
      domainCode: '',
      domainName: '',
      domainDesc: '',
      domainStatus: 'Y'
    }
    let domainInlineSearchVal = {
      domainCode: '',
      domainName: '',
      domainDesc: '',
      domainStatus: ''
    }
    return {
      formInlineSearch: {},
      formInline: JSON.parse(JSON.stringify(domainInlineSearchVal)), // 系统管理高级查询条件
      domainInlineVal: JSON.parse(JSON.stringify(domainInlineVal)), // 新增/编辑弹框里的model,用于重置表单
      domainFormInline: JSON.parse(JSON.stringify(domainInlineVal)), // 系统管理新增/编辑弹框model值
      domainTabelData: [], // 系统管理列表数据
      authorizationData: [], // 点击新增/编辑弹框内的表格获取数据
      domainId: '', // 系统管理列表id
      currentPage: 1, // 当前显示页数
      total: 0, // 显示总页数
      readonly: '', // 设置应用编码不能修改
      allData: [
        {
          userName: '用户名1',
          realName: '员工姓名1'
        },
        {
          userName: '用户名2',
          realName: '员工姓名2'
        }
      ],
      nowPageNum: 0,
      tableData: [],
      pageSize: 20,
      checkDatas: [],
      modalTitle: '',
      delVisible: false, // 删除提示弹框的状态
      dialogVisible: false, // 编辑弹框是否显示
      dialogAddVisible: false, // 新增授权弹框是否显示
      dialogSearch: false, // 高级查询搜索弹框显示
      textSearch: '', // 搜索model值
      searchData: '', // 存储搜索来的数据
      userId: [], // 用户id
      areaData: [], // 获取授权所有数据
      totalUser: 0, // 新增授权用户表格总条数
      currentUserPage: 1, // 新增授权用户当前页
      pageUserSize: 20, //  新增授权用户显示页数
      textSearchUser: '', // 搜索新增授权的用户
    }
  },
  created () {
    this.domainTable()
    this.addAuthorizationEvent()
    window.onresize = () => {
      // console.log(111111)
      this.$refs.areaRefTable.doLayout()
    }
  },
  methods: {
    // 获取系统管理列表数据
    domainTable (currentPage = this.currentPage, pageSize = this.pageSize) {
      let sendDatas = {}
      if (this.dialogSearch) { // 高级查询
        Object.assign(sendDatas, this.formInline)
				this.dialogSearch = false
      } else {
        let textSearch = this.formInlineSearch.textSearch
        if (!textSearch) {
          textSearch = ''
          currentPage = this.currentPage
          pageSize = this.pageSize
        }
        sendDatas.textSearch = textSearch
      }
      ccmsDomainsList(currentPage, pageSize, sendDatas).then(res => {
				console.log(res)
				this.domainTabelData = res.data.data.records || []
        this.total = res.data.data.total || 0
        this.currentPage = currentPage || 1
        setTimeout(() => {
          this.$refs.areaRefTable.doLayout()
        }, 0)
			})
    },
    // 每页条数
		handleSizeChange(val) {
      this.pageSize = val
      this.domainTable()
		},
		// 当前页数
		handleCurrentChange(val) {
      this.currentPage = val
      this.domainTable()
		},
    // 系统管理新增事件
		handleAdd () {
     this.dialogVisible = true
     this.modalTitle = '系统信息'
     this.readonly = false
    //  this.domainFormInline.domainStatus = 'Y'
    },
    // 新增授权表格获取数据事件
		authorizationTabel (row) {
			// this.domainId = row.domainId
			let id = row.domainId
			console.log(id)
      getDomainUser(id).then(res => {
				console.log(res)
        this.authorizationData = res.data.data
        this.authorizationData.forEach((v, i) => {
					this.userId.push(v.userId)
					console.log(this.userId)
				})
			})
		},
    // 编辑事件
    handleEdit (index, row) {
      this.dialogVisible = true
      this.modalTitle = '系统信息'
      this.readonly = true
      this.domainFormInline = JSON.parse(JSON.stringify(row))
      this.authorizationTabel(row) // 点击新增弹框内的表格获取数据事件
    },
     // 保存事件
    handleSave () {
      this.$refs.domainFormInline.validate(valid => {
				if (valid) {
          let userIds = []
          this.authorizationData.forEach(e => {
            userIds.push(e.userId)
          })
          if (!this.domainFormInline.domainId) {
            // 新增接口
            insertCcmsDomain({
              domainCode: this.domainFormInline.domainCode,
              domainName: this.domainFormInline.domainName,
              domainStatus: this.domainFormInline.domainStatus,
              domainDesc: this.domainFormInline.domainDesc,
              userIds: userIds
            }).then(res => {
              console.log(res)
              if (res.data.code === 10000) {
                Message.success('新增成功')
                this.handleClose()
                this.domainTable()
                // this.currentPage = 1
              }
            })
          } else {
            // 编辑接口
            updateCcmsDomainById({
              domainId: this.domainFormInline.domainId,
              domainCode: this.domainFormInline.domainCode,
              domainName: this.domainFormInline.domainName,
              domainStatus: this.domainFormInline.domainStatus,
              domainDesc: this.domainFormInline.domainDesc,
              userIds: userIds
            }).then(res => {
              console.log(res)
              if (res.data.code === 10000) {
                Message.success('编辑成功')
                this.handleClose()
                this.domainTable()
                // this.currentPage = 1
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 点击tabel里的应用状态触发编辑接口事件
		appStatusclick (index, row) {
			updateCcmsDomainById({
				domainId: row.domainId,
        domainCode: row.domainCode,
        domainName: row.domainName,
        domainStatus: row.domainStatus,
        domainDesc: row.domainDesc,
        userIds: []
			}).then(res => {
				if (res.data.code === 10000) {
					Message.success('操作成功')
					this.domainTable()
				}
			})
		},
    // 关闭弹框事件 主要用于清空表单和校验
    handleClose () {
      // let $domainFormInline = this.$refs.domainFormInline
      this.domainFormInline = JSON.parse(JSON.stringify(this.domainInlineVal))
			this.$refs.domainFormInline.resetFields()
      // this.domainFormInline = {}
      this.authorizationData = []
      this.dialogVisible = false
    },
    // 编辑弹框点击按钮
    handleCheck () {
      this.handleClose()
    },
    // 删除员工信息
    handleDelete (index, data){
			MessageBox.confirm('是否确定要删除该行数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
			.then(() => {
				this.delRowData(index, data)
			})
			.catch(() => {})
		},
		// 删除
		delRowData (index, data) {
			// console.log(row)
      let domainAuthId = data[index].domainAuthId
      if (!domainAuthId) {
				data.splice(index, 1)
				return
			}
			cancelDomainAuth([domainAuthId])
			.then(res => {
				console.log(res.data.code)
				if (res.data.code === 10000) {
          Message.success('删除成功')
          data.splice(index, 1)
					// this.authorizationTabel(row) // 删除成功再次调用新增弹框内的表格获取数据事件
				}
			})
			.catch(error => {
				console.log(error)
			})
    },
    // 获取所有授权数据事件
    addAuthorizationEvent() {
      let data = {
        page: this.currentUserPage,
        size: this.pageUserSize
      }
      data.type = 1
      data.userName = this.textSearchUser
      data.name = this.textSearchUser
      userList({
				params: data
			}).then(res => {
        // console.log(res)
        this.areaData = res.data.data.records
        this.totalUser = res.data.data.total
        setTimeout(() => {
					this.$refs.areaRefTable.doLayout() // 表格刷新以后，重绘表格宽度
				}, 0)
      })
    },
    // 新增授权事件
    addAuthorization () {
      this.dialogAddVisible = true
    },
    // 点击复选框
    handleSelectionChange (val) {
      this.checkDatas = val
      // console.log(val)
    },
    // 新增授权弹框里的确认按钮事件
    handDomainleSure () {
      console.log('点击了确定')
      // this.authorizationData = this.authorizationData.concat(this.checkDatas)
      let userIds = []
      this.authorizationData.forEach(e => {
        userIds.push(e.userId)
      })
      this.checkDatas.forEach(e => {
        if (userIds.indexOf(e.userAccountId) == -1) {
          e.userId = e.userAccountId
          e.empName = e.name
					this.authorizationData.push(e)
				}
      })
		  this.handleAddClose()
    },
    // 关闭新增授权按钮
    handleAddClose () {
      this.dialogAddVisible = false
      this.$refs.areaRefTable.clearSelection()
      // this.checkDatas = []
    },
    // 新增授权弹框关闭按钮
    handleCloseCheck () {
      this.handleAddClose()
    },
    // 高级查询事件
		advancedSearch () {
      this.dialogSearch = true
		},
    // 高级查询弹框关闭
		searchClose () {
      this.dialogSearch = false
		},
		// 高级查询点击弹框确定事件
		// handleSearchSure() {
    //   this.domainTable()
		// 	this.searchClose()
		// },
		// 高级查询点击弹框重置事件
		handleSearchClose() {
      this.$refs.formInline.resetFields()
      this.dialogSearch = false
      this.domainTable()
    },
    // 新增授权弹框里分页里每页数据
		handleSizeUserChange (val) {
			this.pageUserSize = val
			this.addAuthorizationEvent()
		},
		// 新增授权弹框里分页里当前页数
    handleCurrentUserChange (val) {
			this.currentUserPage = val
			this.addAuthorizationEvent()
		}
  }
}
</script>
<style lang="scss">
</style>
